<template>
  <template v-if="!item.meta.hidden">
    <el-menu-item v-if="isShowOneMenu" :index="currShowMenu.path" @click="handleClick(currShowMenu)">
      <el-icon>
        <component :is="currShowMenu.meta.icon"></component>
      </el-icon>
      <template #title>
        <span>{{ currShowMenu.meta.title }}</span>
      </template>
    </el-menu-item>

    <el-sub-menu v-else :index="item.path">
      <template #title>
        <el-icon>
          <component :is="item.meta.icon"></component>
        </el-icon>
        <span>{{ item.meta.title }}</span>
      </template>

      <MenuItem v-for="child in item.children" :item="child" :key="child.path"></MenuItem>
    </el-sub-menu>
  </template>
</template>

<script setup>
import {useRouter} from 'vue-router'
import {useTabsStore} from "@/stores/index.js";

defineOptions({name: 'MenuItem'})

const props = defineProps({
  item: {type: Object},
})

// 判断当前菜单是否仅包含一个可显示的子菜单
const isShowOneMenu = ref(false)
const currShowMenu = ref({})
const handleFunction = () => {
  const childrens = props.item?.children?.length ? props.item.children : []
  const showChildrens = childrens.filter(i => i.meta.hidden === false)

  // 没有子菜单需要显示，显示当前
  if (showChildrens.length === 0) {
    isShowOneMenu.value = true
    currShowMenu.value = {...props.item}
  }

  // 只有一个子菜单需要显示，显示仅有的子菜单
  if (showChildrens.length === 1) {
    isShowOneMenu.value = true
    currShowMenu.value = {...showChildrens[0]}
  }
}
handleFunction()

const router = useRouter()

const tabsStore = useTabsStore()
const handleClick = (val) => {
  if (val.path !== router.currentRoute.value.path) {
    tabsStore.addTabItem(val)
  }
}
</script>

<style scoped>

</style>
